package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.domain.Vo.R;
import com.ruoyi.system.domain.Wxcache;
import com.ruoyi.system.service.WxAuthenticationService;
import com.ruoyi.system.service.WxLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxAuthenticationServiceImpl implements WxAuthenticationService {

    @Value("${wx.code2session}")
    private String code2SessionUrl;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;
    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private WxLoginService wxLoginService;

    public R code2Session(String code){
        String url= MessageFormat.format(this.code2SessionUrl,this.appid,this.appsecret,code);
        RestTemplate rest=new RestTemplate();
        Map<String,Object> session=new HashMap<>();
        String sessionText=rest.getForObject(url,String.class);
        try{
            session=mapper.readValue(sessionText, Map.class);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return this.registerUser(session);
    }

    public R registerUser(Map<String,Object> session){
        String openid=(String)session.get("openid");
        String key=(String)session.get("session_key");
        Wxcache wxuser=new Wxcache();
        wxuser.setOpenid(openid);
        wxuser.setWxKey(key);
        System.out.println("wxuser:"+wxuser.toString());
        String Status=wxLoginService.WxLogin(wxuser);
        System.out.println(Status);
        if(Status=="insert"){
            return new R(200,"add session susscess",wxuser);
        }else if(Status =="update"){
            return new R(200,"update session susscess",wxuser);
        }else{
            return new R(200,"ok");
        }
    }

}
